package com.yukino.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.yukino.pojo.User;
import com.yukino.pojo.requestBody.PwdAndCheck;
import com.yukino.pojo.requestBody.RegisterBody;
import com.yukino.pojo.requestBody.UserProfile;
import com.yukino.service.UserService;
import com.yukino.util.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
public class UserInfoController {
    @Autowired
    private UserService userService;

    /**
     * 判断用户名是否存在
     * @param username 用户名
     */
    @GetMapping("/info/exit")
    public AjaxJson isExit(@RequestParam("username") String username) {
        if (!userService.queryUsernameExit(username)) {
            System.out.println("已存在");
            return AjaxJson.getError("用户名已存在，请更换一个用户名");
        } else {
            System.out.println("不存在");
            return AjaxJson.getSuccess();
        }
    }

    /**
     * 创建新用户
     * @param register 创建所提交的信息
     * @return
     */
    @PostMapping("/info/create")
    public AjaxJson create(@RequestBody RegisterBody register) {
        User user = userService.createUser(register);
        System.out.println(user);
        return AjaxJson.getSuccess();
    }

    /**
     * 查询当前用户的资料
     * @return
     */
    @GetMapping("/info/detail")
    public AjaxJson getInfo() {
        String loginId = (String) StpUtil.getLoginId();
        return AjaxJson.getSuccessData(userService.queryInfo(loginId));
    }

    /**
     * 修改密码
     * @param pwdAndCheck 新密码
     * @return
     */
    @PostMapping("/info/updatePwd")
    public AjaxJson updatePwd(@RequestBody PwdAndCheck pwdAndCheck) {
        String loginId = (String) StpUtil.getLoginId();

        String password = pwdAndCheck.getPassword();
        String confirmPassword = pwdAndCheck.getConfirmPassword();
        if (!password.equals(confirmPassword)) return AjaxJson.getError("两次密码不一致");
        else {
            userService.updatePwd(loginId, password);
            return AjaxJson.getSuccess();
        }
    }

    /**
     * 完善信息
     * @param userProfile 更新提交的信息
     * @return
     */
    @PostMapping("/info/updateProfile")
    public AjaxJson updateProfile(@RequestBody UserProfile userProfile) {
        String loginId = (String) StpUtil.getLoginId();
        userService.updateProfile(loginId, userProfile);
        return AjaxJson.getSuccess();
    }
}
